from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.conf import settings
from .redis_pool import POOL
from Login.models import Account
import redis

CONN = redis.Redis(connection_pool=POOL)
NO_URLS = settings.NO_AUTH_URLS


class LoginAuth(BaseAuthentication):
    def authenticate(self, request):
        if request.META.get('PATH_INFO') in NO_URLS:  # 过滤不做校验的接口
            return
        if request.method == "OPTIONS":  # 过滤不做校验的接口类型
            return
        # 从请求头中获取前端带过来的token
        token = request.META.get("HTTP_ACCOUNTTOKEN", "")
        if not token:
            raise AuthenticationFailed("没有携带token")
        # 去redis比对
        user_id = CONN.get(str(token))
        if user_id == None:
            raise AuthenticationFailed("token过期")
        user_obj = Account.objects.filter(id=user_id).first()
        return user_obj, token
